<template>
  <el-container class="app-container">
    <el-collapse @change="handleCollapseChange" v-model="collapseActiveName">
      <el-collapse-item :title="collapseTitle" name="1">
        <el-tabs type="border-card">
          <el-form :model="pageInfo" ref="form" label-width="100px" size="medium">
            <el-row>
              <el-col :span="8" :offset="0">
                <el-form-item prop="areaId" label="所属办公空间:">
                  <el-select v-model="pageInfo.areaId" placeholder="请选择">
                    <el-option
                      v-for="item in spaceOptions"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="lesseeName" label="租户：">
                  <el-input v-model.trim='pageInfo.lesseeName' placeholder="请输入名称搜索"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="status" label="招商状态:">
                  <el-select v-model="pageInfo.status" placeholder="请选择">
                    <el-option
                      v-for="item in zsOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="decorationStyle" label="装修:">
                  <el-select v-model="pageInfo.decorationStyle" placeholder="请选择">
                    <el-option
                      v-for="item in zxOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>


              <el-col :span="8" :offset="1">
                <el-button type="primary" icon="el-icon-search" @click='getData'>搜索</el-button>
                <!--                  <el-button @click="resetForm">重置</el-button>-->
              </el-col>
            </el-row>
          </el-form>
        </el-tabs>
      </el-collapse-item>
    </el-collapse>
    <el-header class="m-t-20">
      <el-button type="primary" icon="el-icon-plus" @click="addOne">房源</el-button>
    </el-header>

    <!--表格-->
    <table-view
      :columns="tableContent"
      :pageList="columnData"

      :templateDiv="{operation:true,status:true}"
    >
      <template slot="operation" slot-scope="scope">
        <el-row class="tx-l">
          <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'update')">编辑</el-button>
          <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'houseDetail')">房源详情</el-button>
          <!--        <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'view')">详情</el-button>-->
          <el-button v-if="!!scope.row.contractId" size="mini" type="primary" @click="editBtnClick(scope.row ,'contractDetail')">合同详情</el-button>
          <el-button size="mini" type="primary" @click="editBtnClick(scope.row ,'gianDetail')">增值收益</el-button>
          <el-button size="mini" type="danger" @click="editBtnClick(scope.row ,'delete')">删除</el-button>
        </el-row>
      </template>
      <template slot="status" slot-scope="scope">
        {{{'0':'可用', '2':'已租', '1':'已定' ,'3':'即将到期','-1':'逾期'}[scope.row.status.toString()]}}
      </template>
    </table-view>

    <!--分页-->
    <pagination-view :pagesize="pageInfo.pageSize"
                     :currentPage="pageInfo.pageNumber"
                     :total="total"
                     @size-change="sizeChange"
                     @current-change="pageChange"
    ></pagination-view>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%"
               :destroy-on-close="true" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="width: 90%">
        <el-form-item prop="areaId" label="所属办公空间:">
          <el-select v-model="form.areaId" placeholder="请选择">
            <el-option
              v-for="item in spaceOptions"
              :key="item.id"
              :label="item.areaName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="buildingNo" label="楼号/楼层/房号:">
          <el-input v-model.trim="form.buildingNo" style="width: 200px" type="number"></el-input>
          幢
          <el-input v-model.trim="form.buildingFloor" style="width: 200px" type="number"></el-input>
          楼
          <el-input v-model.trim="form.roomNo" style="width: 200px" type="number"></el-input>
          室
        </el-form-item>
        <el-form-item prop="measureArea" label="面积（m²）:" placeholder="可租赁面积">
          <el-input v-model.trim="form.measureArea" style="width: 300px" type="number"></el-input>
        </el-form-item>
        <el-form-item prop="decorationStyle" label="装修:">
          <el-radio-group v-model="form.decorationStyle">
            <el-radio-button v-for='item in $const.ZXOPTIONS' :key="item.value" :label="item.value">{{item.label}}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="rentPrice" label="预租单价:">
          <el-input v-model.trim="form.rentPrice" style="width: 200px" type="number"></el-input>
          <el-radio-group v-model="form.priceUnit">
            <el-radio :label="1">元/㎡/天</el-radio>
            <el-radio :label="2">元/月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="vacantDate" label="空置起算日:">
          <el-date-picker
            v-model="form.vacantDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
          <span class="form-item-tip">* 即房源成本开始计算的日期（默认为该房源添加的日期）</span>
        </el-form-item>
        <el-form-item prop="status" label="招商状态:">
          <el-radio-group v-model="form.status">
            <el-radio v-for='item in $const.ZSOPTIONS' :key="item.value" :disabled="zsOptionsDisabled" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remark" label="房源备注:">
          <el-input v-model.trim="form.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="收益明细" :visible.sync="dialogAddDetail" width="60%"
               :destroy-on-close="true">
      <!--表格-->
      <table-view
        :columns="tableContentsymx"
        :pageList="columnDatasymx"
        :templateDiv="{labelIds:true}"
      >
        <template slot="labelIds" slot-scope="scope">
          <el-tag
            class="tags"
            v-for="(item,i) in scope.row.labelIds"
            :key="i"
            :type="success"
            effect="dark">
            {{ item }}
          </el-tag>
        </template>
      </table-view>
      <!--分页-->
      <div style="padding-bottom: 60px">
        <pagination-view
          :pagesize="gainPage.pageSize"
          :currentPage="gainPage.pageNumber"
          :total="gainPageTotal"
          @size-change="gainSizeChange"
          @current-change="gainPageChange"
        ></pagination-view>
      </div>
    </el-dialog>
    <el-footer></el-footer>
  </el-container>
</template>

<script>
  import TableView from '@/components/TableView'
  import ImgUpload from '@/components/ImgUpload'

  import PaginationView from '@/components/PaginationView'
  import * as pageApi from '@/api/spaceBusiness/houseManage'
  import * as spaceApi from '@/api/spaceBusiness/spaceManage'


  export default {
    name: 'list',
    components: {
      TableView,
      PaginationView,
      ImgUpload
    },
    data() {
      const validator = (rule, value, cb) => {
        if (!value || !this.form.buildingFloor || !this.form.roomNo) {
          cb(new Error('请输入完整的楼号/楼层/房号'))
        } else {
          cb()
        }
      }
      const rentPriceValidator = (rule, value, cb) => {
        if (this.form.priceUnit && !value) {
          cb(new Error('请输入面积'))
        } else {
          cb()
        }
      }
      return {
        dialogAddDetail: false,
        spaceOptions: [],
        zsOptions: [{label: '全部', value: ''}].concat(this.$const.ZSOPTIONS),
        zxOptions: [{label: '全部', value: ''}].concat(this.$const.ZXOPTIONS),
        dialogTitle: '添加',
        dialogVisible: false,
        dialogType: 'add',
        tableContentsymx: [{
          field: 'tenantryName',
          label: '租户主体'
        }, {
          field: 'labelIds',
          label: '服务项'
        }, {
          field: 'price',
          label: '金额（收入/支出）'
        }, {
          field: 'operator',
          label: '来源（操作人）'
        }, {
          field: 'createdTime',
          label: '时间'
        }, {
          field: 'remark',
          label: '备注'
        }],
        tableContent: [{
          field: 'areaName',
          label: '所属办公空间'
        },{
          field: 'buildingNo',
          label: '楼号',
          // sortable: true
        }, {
          field: 'buildingFloor',
          label: '楼层',
          // sortable: true
        }, {
          field: 'roomNo',
          label: '房号',
          // sortable: true
        }, {
          field: 'measureArea',
          label: '面积(m²)',
          // sortable: true
        }, {
          field: 'lesseeName',
          label: '租户',
        }, {
          field: 'rentalDate',
          label: '计租日',
          // sortable: true
        }, {
          field: 'rentalDueDate',
          label: '结束日',
          // sortable: true
        }, {
          field: 'price',
          label: '合同单价',
          // sortable: true
        }, {
          field: 'timelyPrice',
          label: '实时单价',
          // sortable: true
        }, {
          field: 'nextRentPaymentDate',
          label: '下期租金付款日',
          // sortable: true
        }, {
          field: 'nextPropertyPaymentDate',
          label: '下期物业费付款日',
          // sortable: true
        }, {
          field: 'status',
          label: '状态',
        }, {
          field: 'remark',
          label: '备注',
        }, {
          field: 'operation',
          label: '操作',
          width: 500
        },],
        columnData: [],
        customWidth: '',
        pageInfo: {
          pageNumber: 1,
          pageSize: 20,
          areaId: '',
          decorationStyle: '',
          lesseeName: '',
          status: ''
        },
        total: 0,
        zsOptionsDisabled:false,
        form: {
          "areaId": '',
          "buildingFloor": "",
          "buildingNo": "",
          "decorationStyle": '',
          "measureArea": '',
          "priceUnit": '',
          "remark": "",
          "rentPrice": '',
          "roomNo": "",
          "status": '',
          "vacantDate": ""
        },
        rules: {
          areaId: [{required: true, trigger: 'change', message: '请选择所属办公空间'}],
          buildingNo: [{required: true, trigger: 'blur', validator: validator}],
          measureArea: [{required: true, trigger: 'change', message: '请输入面积'}],
          status: [{required: true, trigger: 'blur', message: '请选择招商状态'}],
          rentPrice: [{trigger: 'blur', validator: rentPriceValidator}],
        },
        columnDatasymx: [],
        gainPage: {
          pageNumber: 1,
          pageSize: 20,
          roomId: '',
        },
        gainPageTotal: 0
      }
    },
    watch: {},
    methods: {
      //拉取空间list
      getSpaceList() {
        // spaceApi.getList({pageSize: 200})
        spaceApi.getAreaAll().then(res => {
          this.spaceOptions = res.body
        })
      },
      addOne() {
        this.formReset()
        this.dialogVisible = true
        this.dialogTitle = '添加'
        this.dialogType = 'add'
        this.zxOptions = [
          {label:'可租',value:0},{label:'已预订',value:1}
        ]
      },

      onSubmit() {
        let form = this.form
        let dialogType = this.dialogType
        this.$refs['form'].validate((valid) => {
          if (valid) {
            switch (dialogType) {
              case 'add':
                pageApi.create(form).then(res => {
                  this.handleRes(res)
                })
                break
              case 'update':
                pageApi.update(form.id, form).then(res => {
                  this.handleRes(res)
                })
                break
            }
          }
        })
      },
      formReset() {
        this.form = {
          "areaId": '',
          "buildingFloor": "",
          "buildingNo": "",
          "decorationStyle": '',
          "measureArea": '',
          "priceUnit": '',
          "remark": "",
          "rentPrice": '',
          "roomNo": "",
          "status": '',
          "vacantDate": ""
        }
      },
      handleRes(res) {
        this.handleMessage(res)
        if (res.code === '200') {
          this.dialogVisible = false
          this.getData()
        }
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.getData()
      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val
        this.getData()
      },
      editBtnClick(val, type) {
        switch (type) {
          case 'update':
            // this.dialogType =
            this.dialogTitle = '编辑'
            if(val.contractId){
              // this.zsOptionsDisabled = true
            }
            debugger
            this.formReset()
            pageApi.getById(val.id).then(res => {
              this.form = Object.assign({}, this.form, res.body.room)
            })
            this.dialogType = type
            this.dialogVisible = true
            break
          case 'houseDetail':
            let roomDetail = {
              measureArea:val.measureArea,
              areaName:val.areaName,
              buildingNo:val.buildingNo,
              buildingFloor:val.buildingFloor,
              roomNo:val.roomNo
            }
            this.$router.push({name: 'houseDetail', query: {id: val.id,roomDetail:JSON.stringify(roomDetail)}})
            break
          case 'contractDetail':
            this.$router.push({name: 'contractDetail', query: {id: val.contractId}})
            break
          case 'gianDetail':
            this.dialogAddDetail = true
            this.gainPage.roomId = val.id
            this.getGain()
            break
          case 'delete':
            this.$confirm(`确定删除吗？是否继续?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.deleteIt(val.id)
            })
            break
        }
      },
      deleteIt(id){
        pageApi.deleteIt(id).then(res=>{
          this.handleRes(res)
        })
      },
      //拉取列表
      getData() {
        pageApi.getList(this.pageInfo).then(res => {
          this.columnData = res.body.objects
          this.total = Number(res.body.recordTotal)
          this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        })
      },
      getGain() {
        pageApi.getGain(this.gainPage).then(res => {
          this.columnDatasymx = res.body.objects
          this.gainPageTotal = Number(res.body.recordTotal)
          this.gainPage.pageNumber = Number(res.body.pageNumber) || 1
        })
      },
      gainSizeChange(val) {
        this.gainPage.pageSize = val
        this.getGain()
      },
      gainPageChange(val) {
        this.gainPage.pageNumber = val
        this.getGain()
      },
      handleClose(done) {
        let resetForm = {
          costAmount: '',
          courseProductId: '',
          duration: '',
          durationTime: '',
          enable: true,
          intro: '',
          memo: '',
          productName: '',
          saleAmount: '',
          sort: '',
          tag: ''
        }
        this.form = Object.assign({}, this.form, resetForm)
        done()
      }

    },
    mounted() {
      this.getData()
      this.getSpaceList()
      console.log(this.$const.ZSOPTIONS);
    }
  }
</script>

<style lang="scss" scoped>

</style>
